package cn.javaxc.mvcwork.util.common;
import cn.javaxc.mvcwork.controller.MVCConfig;
import java.io.*;
import java.net.URL;
import java.util.*;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.*;




public class XMLUtils
{
  private Document document = null;
  private StringBuffer XMLString = null;
  private boolean cacheXML = false;

  public XMLUtils(String paramString, boolean paramBoolean)
    throws Exception
  {
    if (paramBoolean)
      parseXML(paramString);
    else
      this.document = createDocument(paramString);
  }

  public static Document createDocument()
    throws Exception
  {
    DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
    return localDocumentBuilder.newDocument();
  }

  public static Document createDocument(String paramString)
    throws Exception
  {
    DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
    Document localDocument = localDocumentBuilder.newDocument();
    Element localElement = localDocument.createElement(paramString);
    localDocument.appendChild(localElement);
    return localDocument;
  }

  public XMLUtils(String paramString)
    throws Exception
  {
    parseXML(paramString);
  }

  public XMLUtils(InputStream paramInputStream)
    throws Exception
  {
    parseXML(paramInputStream);
  }

  public XMLUtils(HttpServletRequest paramHttpServletRequest)
    throws Exception
  {
    StringBuffer localStringBuffer = new StringBuffer();
    BufferedReader localBufferedReader = paramHttpServletRequest.getReader();
    String str = null;
    if (System.getProperty("DEBUG") != null)
      System.out.println("XMLUtils->Reading XML from request");
    while ((str = localBufferedReader.readLine()) != null)
    {
      localStringBuffer.append(str.trim() + System.getProperty("line.separator"));
      if (!this.cacheXML)
        continue;
      if (this.XMLString == null)
        this.XMLString = new StringBuffer();
      this.XMLString.append(str);
    }
    if (System.getProperty("DEBUG") != null)
      System.out.println("  XML: " + localStringBuffer.toString());
    parseXML(localStringBuffer.toString());
  }

  public XMLUtils(File paramFile)
    throws Exception
  {
    parseXML(paramFile);
  }

  public XMLUtils(ServletContext paramServletContext, String paramString)
    throws Exception
  {
    if (paramServletContext.getResource(paramString) != null)
    {
      InputStream localInputStream = paramServletContext.getResourceAsStream(paramString);
      DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
      this.document = localDocumentBuilder.parse(localInputStream);
    }
    else
    {
      System.out.println("XMLUtils-> Resource not found: " + paramString);
    }
  }

  public XMLUtils(URL paramURL)
    throws Exception
  {
    InputStream localInputStream = paramURL.openStream();
    DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
    this.document = localDocumentBuilder.parse(localInputStream);
    localInputStream.close();
  }

  public static Element getFirstChild(Document paramDocument, String paramString)
  {
    Element localElement = paramDocument.getDocumentElement();
    return getFirstChild(localElement, paramString);
  }

  public static Element getFirstChild(Element paramElement, String paramString)
  {
    NodeList localNodeList = paramElement.getChildNodes();
    for (int i = 0; i < localNodeList.getLength(); i++)
    {
      Node localNode = localNodeList.item(i);
      if ((localNode != null) && (localNode.getNodeType() == 1) && (((Element)localNode).getTagName().equals(paramString)))
        return (Element)localNode;
    }
    return null;
  }

  public static void getAllChildren(Element paramElement, AbstractList paramAbstractList)
  {
    NodeList localNodeList = paramElement.getChildNodes();
    for (int i = 0; i < localNodeList.getLength(); i++)
    {
      Node localNode = localNodeList.item(i);
      if (localNode.getNodeType() != 1)
        continue;
      paramAbstractList.add((Element)localNode);
    }
  }

  public static void getAllChildren(Element paramElement, String paramString, AbstractList paramAbstractList)
  {
    NodeList localNodeList = paramElement.getChildNodes();
    for (int i = 0; i < localNodeList.getLength(); i++)
    {
      Node localNode = localNodeList.item(i);
      if ((localNode.getNodeType() != 1) || (!((Element)localNode).getTagName().equals(paramString)))
        continue;
      paramAbstractList.add((Element)localNode);
    }
  }

  public static void getAllChildrenText(Element paramElement, String paramString, AbstractList paramAbstractList)
  {
    NodeList localNodeList = paramElement.getChildNodes();
    for (int i = 0; i < localNodeList.getLength(); i++)
    {
      Node localNode = localNodeList.item(i);
      if ((localNode.getNodeType() != 1) || (!((Element)localNode).getTagName().equals(paramString)))
        continue;
      String str = getNodeText((Element)localNode);
      if (str == null)
        continue;
      paramAbstractList.add(str);
    }
  }

  public static Element getFirstElement(Element paramElement, String paramString)
  {
    try
    {
      XPath localXPath = XPathFactory.newInstance().newXPath();
      Node localNode = (Node)localXPath.evaluate(paramString, paramElement, XPathConstants.NODE);
      return (Element)localNode;
    }
    catch (Exception localException)
    {
      System.out.println("XMLUtils-> Unhandled exception: " + localException.getMessage());
    }
    return null;
  }

  public static NodeList getXElements(Element paramElement, String paramString) throws javax.xml.xpath.XPathExpressionException
  {
    XPath localXPath = XPathFactory.newInstance().newXPath();
    return  (NodeList)localXPath.evaluate(paramString, paramElement, XPathConstants.NODESET);
  }
  private static ArrayList getElements(Element paramElement, String paramString)
  {
    ArrayList localArrayList = new ArrayList();
    try
    {
      XPath localXPath = XPathFactory.newInstance().newXPath();
      NodeList localNodeList = (NodeList)localXPath.evaluate(paramString, paramElement, XPathConstants.NODESET);
      for (int i = 0; i < localNodeList.getLength(); i++)
      {
        Node localNode = localNodeList.item(i);
        if ((localNode.getNodeType() != 1) || (!((Element)localNode).getTagName().equals(paramString)))
          continue;
        localArrayList.add((Element)localNode);
      }
    }
    catch (Exception localException)
    {
      System.out.println("XMLUtils-> Unhandled exception: " + localException.getMessage());
    }
    return localArrayList;
  }

  public static String getNodeText(Node paramNode)
  {
    if (paramNode == null)
      return null;
    NodeList localNodeList = paramNode.getChildNodes();
    for (int i = 0; i < localNodeList.getLength(); i++)
    {
      Node localNode = localNodeList.item(i);
      if ((localNode.getNodeType() == 3) || (localNode.getNodeType() == 4))
        return localNode.getNodeValue();
    }
    return null;
  }

  public static HashMap populateObject(Object paramObject, Element paramElement)
  {
    if ((paramObject != null) && (paramElement != null))
    {
      HashMap localHashMap = new HashMap();
      NodeList localNodeList = paramElement.getChildNodes();
      for (int i = 0; i < localNodeList.getLength(); i++)
      {
        Node localNode = localNodeList.item(i);
        if (localNode.getNodeType() != 1)
          continue;
        String str1 = localNode.getNodeName();
        String str2 = getNodeText(localNode);
        String str3;
        if (ObjectUtils.setParam(paramObject, str1, str2))
        {
          if (System.getProperty("DEBUG") != null)
          {
            str3 = str1.substring(0, 1).toUpperCase() + str1.substring(1);
            System.out.println("XMLUtils-> set" + str3 + "(" + str2 + ")");
          }
          str3 = ((Element)localNode).getAttribute("lookup");
          if (str3 != null)
          {
            localHashMap.put(str1 + "^" + str3 + "Guid", str2);
          }
          else if ((str2 != null) && (str2.indexOf("$C{") > -1))
          {
            if (System.getProperty("DEBUG") != null)
              System.out.println("XMLUtils-> set" + str1 + "(" + str2 + ") **CONTEXT");
            localHashMap.put(str1, str2);
          }
        }
        else
        {
          if (System.getProperty("DEBUG") != null)
          {
            str3 = str1.substring(0, 1).toUpperCase() + str1.substring(1);
            System.out.println("XMLUtils-> set" + str3 + "(" + str2 + ") **IGNORED");
          }
          localHashMap.put(str1, str2);
        }
      }
      return localHashMap;
    }
    return null;
  }

  public static String toXMLValue(String paramString)
  {
    if (paramString != null)
    {
      String str = paramString.trim();
      str = str.replace( "\"", "&quot;");
      str = str.replace( "<", "&lt;");
      str = str.replace( ">", "&gt;");
      return str;
    }
    return "";
  }

  public static String toString(String paramString)
  {
    if (paramString != null)
    {
      String str = paramString.trim();
      str = str.replace( "&quot;", "\"");
      str = str.replace( "&lt;", "<");
      str = str.replace( "&gt;", ">");
      return str;
    }
    return "";
  }

  public static String toString(Node paramNode)
  {
    return toString(paramNode, "UTF-8");
  }

  public static String toString(Node paramNode, String paramString)
  {
    try
    {
      TransformerFactory localTransformerFactory = TransformerFactory.newInstance();
      Transformer localTransformer = localTransformerFactory.newTransformer();
      localTransformer.setOutputProperty("encoding", paramString);
      localTransformer.setOutputProperty("method", "xml");
      DOMSource localDOMSource = new DOMSource(paramNode);
      StringWriter localStringWriter = new StringWriter();
      StreamResult localStreamResult = new StreamResult(localStringWriter);
      localTransformer.transform(localDOMSource, localStreamResult);
      return localStringWriter.toString();
    }
    catch (Exception localException)
    {
      localException.printStackTrace(System.out);
    }
    return null;
  }

  public static void saveXML(Document paramDocument, File paramFile)
    throws TransformerException
  {
    TransformerFactory localTransformerFactory = TransformerFactory.newInstance();
    Transformer localTransformer = localTransformerFactory.newTransformer();
    localTransformer.setOutputProperty("indent", "yes");
    StreamResult localStreamResult = new StreamResult(paramFile);
    DOMSource localDOMSource = new DOMSource(paramDocument);
    localTransformer.transform(localDOMSource, localStreamResult);
  }

  public static boolean debug(Node paramNode)
  {
    try
    {
      TransformerFactory localTransformerFactory = TransformerFactory.newInstance();
      Transformer localTransformer = localTransformerFactory.newTransformer();
      DOMSource localDOMSource = new DOMSource(paramNode);
      StreamResult localStreamResult = new StreamResult(System.out);
      localTransformer.transform(localDOMSource, localStreamResult);
      return true;
    }
    catch (Exception localException)
    {
      localException.printStackTrace(System.out);
    }
    return false;
  }

  public void setCacheXML(boolean paramBoolean)
  {
    this.cacheXML = paramBoolean;
  }

  public Document getDocument()
  {
    return this.document;
  }

  public Element getDocumentElement()
  {
    return this.document.getDocumentElement();
  }

  public String getXMLString()
  {
    if (this.XMLString == null)
      return null;
    return this.XMLString.toString();
  }

  public Element getFirstChild(String paramString)
  {
    return getFirstChild(this.document, paramString);
  }

  public Element getFirstElement(String paramString)
  {
    return getFirstElement(getDocumentElement(), paramString);
  }

  public static Element getElement(Element paramElement, String paramString1, String paramString2, String paramString3)
  {
    ArrayList localArrayList = new ArrayList();
    getAllChildren(paramElement, paramString1, localArrayList);
    Iterator localIterator = localArrayList.iterator();
    while (localIterator.hasNext())
    {
      Element localElement = (Element)localIterator.next();
      if (paramString3.equals(localElement.getAttribute(paramString2)))
        return localElement;
    }
    return null;
  }

  public String toString()
  {
    return toString(this.document);
  }

  private void parseXML(String paramString)
    throws Exception
  {
    StringReader localStringReader = new StringReader(paramString);
    InputSource localInputSource = new InputSource(localStringReader);
    DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
    this.document = localDocumentBuilder.parse(localInputSource);
  }

  private void parseXML(File paramFile)
    throws Exception
  {
    DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
    this.document = localDocumentBuilder.parse(paramFile);
  }

  private void parseXML(InputStream paramInputStream)
    throws Exception
  {
    DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
    this.document = localDocumentBuilder.parse(paramInputStream);
  }
    
  public static boolean loadConfig(String filename, Map config) {
    if (filename.endsWith(".xml")) {
      File file = new File(filename);
      if (file == null) {
        System.err.println(
            "AppUtils-> Configuration file not found: " + filename);
        return false;
      }
      try {
        Document document = parseDocument(file);
        config.clear();
        NodeList tags = document.getElementsByTagName("init-param");
        for (int i = 0; i < tags.getLength(); i++) {
          Element tag = (Element) tags.item(i);
          NodeList params = tag.getChildNodes();
          String name = null;
          String value = null;
          for (int j = 0; j < params.getLength(); j++) {
            Node param = (Node) params.item(j);
            if (param.hasChildNodes()) {
              NodeList children = param.getChildNodes();
              Node thisNode = (Node) children.item(0);
              if (param.getNodeName().equals("param-name")) {
                name = thisNode.getNodeValue();
              }
              if (param.getNodeName().equals("param-value")) {
                value = thisNode.getNodeValue();
              }
            }
          }
          if (value == null) {
            value = "";
          }
          config.put(name, value);
        }
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
      return true;
    } else {
      MVCConfig prefs = new MVCConfig();
//      prefs.load(filename + "project.cfg");
      if (!prefs.has("FILELIBRARY")) {
        prefs.add("FILELIBRARY", filename);
      }
      config.putAll(prefs.getPrefs());
      return true;
    }
  }



  private static Document parseDocument(File file)
      throws FactoryConfigurationError, ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(file);
    return document;
  }
}
